package com.atguigu.gmall.oauth.service.impl;

import com.atguigu.gmall.oauth.service.LoginService;
import com.atguigu.gmall.oauth.util.AuthToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.util.Base64;
import java.util.Map;

/**
 * projectName: gmall
 *
 * @author: 陈鹏
 * time: 2022/10/6 19:38 星期四
 * description:
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    /**
     * 自定义登录(帮用户拼参数)
     *
     * @param username
     * @param password
     * @return
     */
    @Override
    public AuthToken login(String username, String password) {

        //校验参数
        if(StringUtils.isEmpty(username) ||
                StringUtils.isEmpty(password)){
            throw new RuntimeException("用户名或密码为空,请重试");
        }
        //请求的url
        //String url = "http://localhost:9001/oauth/token";
        //动态获取url
        ServiceInstance serviceInstance =
                loadBalancerClient.choose("service-oauth");
        String url = serviceInstance.getUri().toString() + "/oauth/token";
        //请求头初始化
        MultiValueMap<String, String> headers = new HttpHeaders();
        headers.set("Authorization",getParams());
        //请求体初始化
        MultiValueMap<String, String> body = new HttpHeaders();
        body.set("username",username);
        body.set("password",password);
        body.set("grant_type","password");
        //请求参数对象初始化
        HttpEntity httpEntity = new HttpEntity(body,headers);
        //发送post请求
        /**
         * 1.请求地址
         * 2.请求方法类型
         * 3.请求参数
         * 4.返回结果类型
         */
        ResponseEntity<Map> exchange = restTemplate.exchange(url, HttpMethod.POST, httpEntity, Map.class);
        //获取结果
        Map<String,String> result = exchange.getBody();
        //令牌
        AuthToken authToken = new AuthToken();
        String access_token = result.get("access_token");
        authToken.setAccessToken(access_token);
        //刷新令牌
        String refresh_token = result.get("refresh_token");
        authToken.setRefreshToken(refresh_token);
        //唯一标识
        String jti = result.get("jti");
        authToken.setJti(jti);
        //返回结果
        return authToken;
    }

    @Value("${auth.clientId}")
    private String clientId;
    @Value("${auth.clientSecret}")
    private String clientSecret;
    /**
     * 拼接请求头中的参数
     * @return
     */
    private String getParams() {
        String result = "Basic ";
        //拼接clientId 和clientSecret
        String a = clientId + ":" + clientSecret;
        //base64加密
        byte[] encode = Base64.getEncoder().encode(a.getBytes());
        //返回
        return result + new String(encode);
    }
}
